<template>
  <div>
    <el-page-header @back="goBack"> </el-page-header>
    <div class="createRole">
      <div class="list" style="min-width: 500px">
        <img src="@/assets/imgs/setting/add.png" class="img" />
        <div class="title">角色权限</div>
        <div class="hint">
          管理平台还提供了四种默认角色「管理员」「运营」「技术」「财务」，默认角色权限可编辑。如果你需要其他角色，可点击「添加」按钮自定义角色权限。
        </div>
        <div class="alert">
          <i class="el-icon-warning"></i>
          <span
            >提交企业审核的成员为系统管理员（支付负责人），系统管理员（支付负责人）拥有全部应用的所有权限。</span
          >
        </div>
        <div class="listItem" v-for="(item, index) of list" :key="item.id">
          <div>
            <div class="type">{{ item.name }}</div>
            <div style="width: 320px">{{ item.remark }}</div>
          </div>
          <el-button
            class="width120"
            :class="editIndex == index ? 'editClass' : ''"
            @click="editInfo(item.id, index)"
            >编辑</el-button
          >
        </div>
      </div>
      <div class="add" style="min-width: 1000px">
        <div class="header">
          <div class="title">
            {{ $route.query.id || id ? "编辑角色" : "添加角色" }}
          </div>
          <div>
            <el-button
              class="width120"
              v-if="
                ($route.query.id || id) && (list[editIndex]?list[editIndex].roleType:'') == 'default'
              "
              @click="defaultFn"
              style="min-width: 160px"
              >恢复默认菜单</el-button
            >
            <el-button class="width120" @click="goBack">取消</el-button>
            <el-button class="width120" type="primary" @click="saveRole"
              >提交</el-button
            >
          </div>
        </div>
        <el-form
          ref="rolePerForm"
          :model="form"
          :rules="rules"
          label-width="90px"
          style="margin-left: 34px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input
              v-model="form.name"
              style="width: 604px"
              maxlength="15"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="权限说明">
            <el-input
              v-model="form.remark"
              style="width: 604px"
              maxlength="32"
              show-word-limit
            ></el-input>
          </el-form-item>
          <div class="titleR">企业面板权限</div>
          <el-checkbox
          :disabled="qyShow"
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <el-checkbox-group
            v-model="checkedCities"
            @change="handleCheckedCitiesChange"
            style="margin-left: 24px"
          >
            <el-checkbox
            :disabled="qy_item.disabled"
              v-for="qy_item in cities"
              :label="qy_item.id"
              :key="qy_item.id"
              >{{ qy_item.name }}</el-checkbox
            >
          </el-checkbox-group>
          <div class="titleR marginT">应用权限</div>
          <div v-for="(item, i) of menuList" :key="i">
            <el-checkbox
            :disabled="item.disabled"
              v-if="item.children.length"
              :indeterminate="item.isIndeterminate"
              v-model="item.checkAll"
              @change="handleCheckAllChange2($event, i)"
              >{{ item.name }}</el-checkbox
            >
            <el-checkbox-group
              v-model="item.checkedCities"
              @change="handleCheckedCitiesChange2($event, i)"
            >
              <div v-if="item.children.length" style="margin-left: 24px">
                <el-checkbox
                :disabled="child.disabled"
                  v-for="child in item.children"
                  :label="child.id"
                  :key="child.id"
                  >{{ child.name }}</el-checkbox
                >
              </div>
              <el-checkbox v-else :label="item.id" :key="item.id" :disabled="item.disabled">{{
                item.name
              }}</el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="titleR marginT">操作权限</div>
          <div class="alertR">
            <i class="el-icon-warning"></i>
            <div>
              除系统管理员外，其他成员不可同时拥有退款、退款审核2个权限，提现、提现审核亦然。
            </div>
          </div>
          <div style="display:flex">
            <el-checkbox v-model="refundBtn" :disabled="checkedPerm||refundShow">退款</el-checkbox>
            <el-checkbox v-model="checkedPerm" :disabled="refundBtn||refundShow1">退款审核</el-checkbox>
          </div>
          <div class="hintR" v-if="refundBtn">
            包含支付订单、支付订单批量退款、充值记录管理处的退款权限
          </div>
          <div class="hintR" v-if="checkedPerm">
            开启“退款审核”权限后，还需要在应用内开启“退款审核开关”，不然订单退款时不需要进行审核；
            <br>
            关闭“退款审核”权限时，建议先去关闭“退款审核开关”避免出现订单进入“退款审核”页面，没有人可以审核的情况；
          </div>
          <br>
          <div style="display:flex">
            <el-checkbox v-model="withdrawBtn" :disabled="withdrawPerm||withdrawShow">提现</el-checkbox>
            <el-checkbox v-model="withdrawPerm" :disabled="withdrawBtn||withdrawShow1">提现审核</el-checkbox>
          </div>
          <div class="hintR" v-if="withdrawBtn">
            我的钱包中发起提现申请权限
          </div>
          <div class="hintR" v-if="withdrawPerm">
            开启“提现审核”权限后，还需要在应用内开启“提现审核开关”，不然发起提现申请时不需要进行审核；
            <br>
关闭“提现审核”权限时，建议先去关闭“提现审核开关”避免出现订单进入“提现审核”页面，没有人可以审核的情况；
          </div>
          <!-- <el-checkbox v-model="collectMoney">汇总金额</el-checkbox>
            <div class="hintR">包含首页日交易额交易量、支付订单汇总金额、业务订单汇总金额、分账结算应付账款汇总金额&分账结算应收账款汇总金额、子商户交易概览汇总金额、子商户交易查询
                财务汇总&子商户交易查询支付订单查询、余额账户管理平台账户余额（存管余额）、赠送余额账户管理-平台受赠余额、充值记录管理汇总金额</div> -->
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "addRole",
  data() {
    return {
      qyShow:false,//企业面板全选按钮启用禁用
      refundShow:false,//退款启用禁用
      refundShow1:false,//退款审核启用禁用
      withdrawShow:false,//提现启用禁用
      withdrawShow1:false,//提现审核启用禁用
      id: "",
      editIndex: null,
      form: {
        name: "",
        remark: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "change" },
          {
            pattern: /^(?!\s+).*(?<!\s)$/,
            message: "格式有误",
            trigger: "change",
          },
          {
            min: 1,
            max: 15,
            message: "长度在 1 到 15 个字符",
            trigger: "change",
          },
        ],
      },
      list: [],
      checkAll: false,
      checkedCities: [],
      cities: [],
      isIndeterminate: true,
      menuList: [],
      refundBtn: false,
      checkedPerm: false,
      withdrawBtn: false,
      withdrawPerm: false,
      collectMoney: false,
      operationButtons: [],
      userMenus: "",
    };
  },
  created() {
    this.$http.post("/role/all").then((res) => {
      if (res.code === "0000") {
        this.list = res.data;
      }
    });
    const id = this.$route.query.id;
    this.$http.get("/role/listMenuForSaveRole").then((res) => {
      if (res.code === "0000") {
        this.menuList = res.data.merchantMenus.map((item) => ({
          ...item,
          isIndeterminate: true,
          checkAll: false,
          checkedCities: [],
        }));
                res.data.companyMenus.forEach(e => {
                    if(e.disabled){
            this.qyShow=true
                      }
                    });
            this.cities = res.data.companyMenus;
        this.operationButtons = res.data.operationButtons;
        this.operationButtons.forEach(e => {
          if(e.type=='refund'){
            this.refundShow=e.disabled
          }
          if(e.type=='refundApply'){
            this.refundShow1=e.disabled
          }
          if(e.type=='withdrawal'){
            this.withdrawShow=e.disabled
          }
          if(e.type=='withdrawalApply'){
            this.withdrawShow1=e.disabled
          }
                    });
        this.userMenus = res.data.userMenus[0].id;
        if (id) {
          this.editIndex = this.$route.query.index;
          this.getInfoById(id);
        }
      }
    });
  },
  methods: {
    defaultFn() {
      // var params = new FormData();
      // params.append("roleId", this.id);
      let params = {
        roleId: this.id
      };
      this.$http.post("/role/resetDefaultRoleMenu", params).then((res) => {
        if (res.code == "0000") {
          this.$message.success("恢复成功！");
          this.getInfoById(this.id);
        }
      });
    },
    goBack() {
      this.$backTo(`/qiye/rolePermissions`);
    },
    getInfoById(id) {
      this.id = id;
      this.$http
        .get("/role/get", {
          params: { id },
        })
        .then((res) => {
          this.form = {
            name: res.data.name,
            remark: res.data.remark,
          };
          this.checkedCities =
            res.data?.companyMenus?.map((item) => item.id) || [];
          this.checkAll = this.checkedCities.length === this.cities.length;
          this.isIndeterminate = !this.checkAll;
          const arr =
            res.data?.operationButtons?.map((item) => item.type) || [];
          this.refundBtn = arr.includes("refund");
          this.checkedPerm = arr.includes("refundApply");
          this.withdrawBtn = arr.includes("withdrawal");
          this.withdrawPerm = arr.includes("withdrawalApply");
          this.collectMoney = arr.includes("gatherAmount");
          const merchantList = res.data?.merchantMenus || [];
          merchantList.forEach((val) => {
            const info = this.menuList.find((v) => v.id === val.id);
            info.checkedCities = val.children.length
              ? [...val.children.map((vvv) => vvv.id)]
              : [val.id];
            info.checkAll = info.children.length === val.children.length;
            info.isIndeterminate = !info.checkAll;
          });
        });
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities.map((item) => item.id) : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    handleCheckAllChange2(val, i) {
      this.menuList[i].checkedCities = val
        ? this.menuList[i].children.map((v) => v.id)
        : [];
      this.menuList[i].isIndeterminate = false;
    },
    handleCheckedCitiesChange2(value, i) {
      let checkedCount = value.length;
      this.menuList[i].checkAll =
        checkedCount === this.menuList[i].children.length;
      this.menuList[i].isIndeterminate =
        checkedCount > 0 && checkedCount < this.menuList[i].children.length;
    },
    saveRole() {
      this.$refs.rolePerForm.validate((valid) => {
        if (valid) {
          let menuIdList = [...this.checkedCities];
          let selectSpecialIds = [];
          this.menuList.forEach((val) => {
            if (val.checkedCities.length) {
              menuIdList.push(val.id, ...val.checkedCities);
            }
          });
          if (this.refundBtn) {
            const arr = this.operationButtons.find(
              (item) => item.type === "refund"
            ).ids;
            selectSpecialIds.push(...arr);
          }
          if (this.checkedPerm) {
            const arr = this.operationButtons.find(
              (item) => item.type === "refundApply"
            ).ids;
            selectSpecialIds.push(...arr);
          }
          if (this.withdrawBtn) {
            const arr = this.operationButtons.find(
              (item) => item.type === "withdrawal"
            ).ids;
            selectSpecialIds.push(...arr);
          }
          if (this.withdrawPerm) {
            const arr = this.operationButtons.find(
              (item) => item.type === "withdrawalApply"
            ).ids;
            selectSpecialIds.push(...arr);
          }
          if (this.collectMoney) {
            const arr = this.operationButtons.find(
              (item) => item.type === "gatherAmount"
            ).ids;
            selectSpecialIds.push(...arr);
          }
          menuIdList.push(this.userMenus);
          if (this.id) {
            this.$http
              .post("/role/update", {
                menuIdList,
                name: this.form.name,
                remark: this.form.remark,
                roleType: "other",
                id: this.id,
                selectSpecialIds,
              })
              .then((res) => {
                if (res.code === "0000") {
                  this.$message.success("编辑成功！");
                  this.goBack();
                }
              });
          } else {
            this.$http
              .post("/role/save", {
                menuIdList,
                name: this.form.name,
                remark: this.form.remark,
                roleType: "other",
                selectSpecialIds,
              })
              .then((res) => {
                if (res.code === "0000") {
                  this.$message.success("添加成功！");
                  this.goBack();
                }
              });
          }
        }
      });
    },
    editInfo(id, index) {
      this.editIndex = index;
      this.menuList = this.menuList.map((item) => ({
        ...item,
        isIndeterminate: true,
        checkAll: false,
        checkedCities: [],
      }));
      this.getInfoById(id);
    },
  },
};
</script>

<style lang="scss" scoped>
.createRole {
  display: flex;
  .list {
    width: 30%;
    padding: 36px 30px 0 40px;
    background: #fff;
    .img {
      width: 86px;
      height: 86px;
    }
    .title {
      font-size: 20px;
      font-weight: 600;
      color: #4f595f;
      line-height: 37px;
      margin-top: 20px;
    }
    .hint {
      color: #869daa;
      line-height: 22px;
      font-weight: 400;
    }
    .alert {
      height: 70px;
      background: #fff9f9;
      border-radius: 6px;
      border: 1px solid #f7d8d8;
      color: #fc8f90;
      display: flex;
      padding: 8px 20px;
      margin-top: 28px;
      .el-icon-warning {
        margin-right: 20px;
        font-size: 16px;
        margin-top: 5px;
      }
      span {
        line-height: 26px;
      }
    }
    .listItem {
      height: 112px;
      padding: 35px 0;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #f0f0f0;
      color: #666;
      .type {
        font-size: 16px;
        font-weight: 500;
        color: #4f595f;
        margin-bottom: 8px;
      }
      .editClass {
        background: rgb(230, 249, 249);
        color: #03bfc6;
        border: 1px solid rgb(179, 236, 238);
      }
    }
    .first {
      margin-top: 45px;
      border-top: 1px solid #f0f0f0;
    }
  }
  .add {
    flex: 1;
    margin-left: 20px;
    background: #fff;
    padding-bottom: 50px;
    .title {
      font-size: 24px;
      font-weight: 500;
      height: 40px;
      line-height: 40px;
      color: #25b5d9;

      position: relative;
      &::before {
        content: "";
        width: 104px;
        height: 10px;
        background: #25b5d9;
        border-radius: 5px;
        position: absolute;
        top: 55px;
      }
    }
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 40px 20px 70px;
      border-bottom: 1px solid #f0f0f0;
      margin-bottom: 40px;
    }
    .titleR {
      color: #4f595f;
      position: relative;
      font-size: 20px;
      font-weight: 600;
      line-height: 34px;
      margin: 34px 0;
      &::before {
        content: "";
        width: 4px;
        height: 24px;
        background: #03bfc6;
        position: absolute;
        left: -34px;
        top: 5px;
      }
    }
    .marginT {
      margin-top: 14px;
    }
    .alertR {
      width: 834px;
      background: #fff9f9;
      border-radius: 6px;
      border: 1px solid #f7d8d8;
      color: #fc8f90;
      display: flex;
      padding: 8px 20px;
      margin-top: -20px;
      margin-bottom: 20px;
      .el-icon-warning {
        margin-right: 20px;
        font-size: 16px;
        margin-top: 5px;
      }
      div {
        line-height: 26px;
      }
    }
    .hintR {
      color: #869daa;
      margin-top:-10px;
      margin-bottom: 20px;
      line-height: 20px;
    }
    :deep(.el-checkbox) {
      margin-bottom: 20px;
    }
  }
}
</style>
